package com.hub.nio.socket.nio;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ author 令狐冲
 * @ date & time 2025/2/5 9:35
 */
public class FileNoZeroCopy {

    public static void main(String[] args) {
        long beginTime = System.currentTimeMillis();
        File source = new File("source.txt");
        File target = new File("target.txt");

        try (FileInputStream sourceInputStream = new FileInputStream(source); FileOutputStream targetOutputStream = new FileOutputStream(target)) {
            FileChannel isChannel = sourceInputStream.getChannel();
            FileChannel osChannel = targetOutputStream.getChannel();

            ByteBuffer buf = ByteBuffer.allocate(1024);

            while (true) {
                // 读数据
                int flag = isChannel.read(buf);
                if (flag == -1) {
                    break;
                }
                //读模式
                buf.flip();
                //写数据
                osChannel.write(buf);
                //清空buffer
                buf.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("传统IO共耗时：" + (System.currentTimeMillis() - beginTime));
    }
}
